const axios = require('axios');
const { ipcMain } = require('electron');
const { WEACHER_URL } = require('../config/config');

function getWeather(event) {
    axios.get(WEACHER_URL, {
        headers: {
            Referer: 'http://www.weather.com.cn/',
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36',
        },
    }).then((data) => {
        let weather = '';
        try {
            const result = data.data;
            if (result) {
                const weatherArr = result.match(/({.+}})/);
                weather = weatherArr.length > 1 ? weatherArr[1] : '';
            }
            event.sender.send('bindRenderChangeWeather', { data: JSON.parse(weather), status: 'ok' });
        } catch (e) {
            event.sender.send('bindRenderChangeWeather', { data: {}, status: 'error' });
        }
    }).catch((err) => {
        console.log(err);
        event.sender.send('bindRenderChangeWeather', { data: {}, status: 'error' });
    });
}

function execChild(event, args) {

}

// render初始化完成事件
ipcMain.on('bindRenderInitEvent', (event, args) => {
    if (typeof args === 'string') {
        if (args === 'getWeather') {
            getWeather(event);
        }
    } else if (typeof args === 'object') {
        execChild(event, args);
    }
});

ipcMain.on('onDropCompress', (event, files) => {
    console.log(files);
    event.sender.send('onDropCompressFinish', 'ok');
});

